package com.example.task;

import org.flowable.engine.ProcessEngine;
import org.flowable.task.api.Task;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class TaskController {
    @Resource
    private ProcessEngine engine;

    @GetMapping("/listTask/{userId}")
    public List<Map<String, Object>> listTask(@PathVariable String userId) {
        List<Task> list = engine.getTaskService().createTaskQuery().taskCandidateOrAssigned(userId).list();
        return list.stream().map(s -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("id", s.getId());
                    result.put("processInstanceId", s.getProcessInstanceId());
                    result.put("processDefinitionId", s.getProcessDefinitionId());
                    result.put("executionId", s.getExecutionId());
                    result.put("name", s.getName());
                    result.put("createTime", s.getCreateTime());
                    result.put("formKey", s.getFormKey());
                    result.put("dueDate", s.getDueDate());
                    result.put("claimTime", s.getClaimTime());
                    return result;
                }
        ).collect(Collectors.toList());
    }

    @PostMapping("/completeTaskWithVariables/{userId}/{taskId}")
    public void completeTaskWithVariables(@PathVariable String taskId, @RequestBody Map<String, Object> param, @PathVariable String userId) {
        engine.getTaskService().claim(taskId, userId);
        if (!ObjectUtils.isEmpty(param)) {
            engine.getTaskService().complete(taskId);
        } else {
            engine.getTaskService().complete(taskId, param);
        }
    }
}
